import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';

import '../../utils/http.dart';
import '../../utils/toast.dart';

class NoticeDetail extends StatefulWidget {
  const NoticeDetail({super.key});

  @override
  State<NoticeDetail> createState() => _NoticeDetailState();
}

class _NoticeDetailState extends State<NoticeDetail> {
  Map notifyDetail = {};

  // 注意事项：获取路由参数不能再 initState 中获取，因为此时路由参数还没准备好。
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 获取路由参数
    final id = ModalRoute.of(context)?.settings.arguments;
    if (id != null) {
      // 发送网络请求
      getNotifyDetail(id.toString());
    } else {
      Future.delayed(const Duration(seconds: 0), () {
        ToastUtil.showError('参数失效');
      });
    }
  }

  getNotifyDetail(String id) async {
    try {
      // 请求数据
      var res = await http.get('/announcement/$id');
      if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
      ToastUtil.showSuccess('获取数据成功');
      setState(() {
        notifyDetail = res['data'];
      });
    } catch (e) {
      ToastUtil.showError('请求失败：$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('公告详情'),
      ),
      body: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text(notifyDetail['title'] ?? '',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    )),
                const SizedBox(height: 10),
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(notifyDetail['creatorName'] ?? '',
                          style: const TextStyle(color: Colors.grey)),
                      Text(notifyDetail['createdAt'] ?? '',
                          style: const TextStyle(color: Colors.grey))
                    ]),
                const SizedBox(height: 10),
                // 内容
                Html(
                  data: notifyDetail['content'] ?? '',
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
